<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\OrderEvaluated;
use App\Events\OrderFinished;
use App\Models\MasterStatistic;
use App\Models\Order;
use App\Models\OrderComplain;
use App\Models\OrderEvaluate;
use App\Notifications\OrderNotifications\OrderFinishedNotification;
use DB;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrderEvaluatedListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'order';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderFinished  $event
     * @return void
     */
    public function handle(OrderEvaluated $event)
    {
        $evaluate = OrderEvaluate::find($event->evaluate_id);
        if(!$evaluate){
            throw new \Exception('miss complain');
        }
        if(!$evaluate->order){
            throw new \Exception('miss order');
        }

        $statistic = MasterStatistic::where('master_id',$evaluate->order->master_id)->first();
        if(!$statistic){
            $statistic = MasterStatistic::create([
                'master_id' => $evaluate->order->master_id,
            ]);
        }
        if(!$statistic){
            throw new \Exception('miss master statistic');
        }
        $data = [
            'score_count'=>DB::raw('score_count + 3'),
            'score_sum'=>DB::raw("score_sum + {$evaluate->oe_quality} + {$evaluate->oe_attitude} + {$evaluate->oe_ontime}"),
            'evaluate_count'=>DB::raw('evaluate_count + 1'),
        ];
        if ($evaluate->oe_score == Params::ORDER_EVALUATE_HIGH){
            $data['points'] = DB::raw('points + 1');
            $data['evaluate_praise_count'] = DB::raw('evaluate_praise_count + 1');
        }else if ($evaluate->oe_score == Params::ORDER_EVALUATE_LOW){
            $data['points'] = DB::raw('points - 1');
        }
        $ret = $statistic->update($data);
        if (!$ret){
            throw new \Exception('master statistic update fail');
        }
    }

    public function failed(OrderEvaluated $event, \Exception $exception)
    {
        //
    }
}
